<template>
  <!-- <el-input v-model="databaseConfig.tableName" placeholder="请输入表名"></el-input> -->
  <!-- 管理数据表 -->
  <div
    v-if="databaseConfig && databaseConfig.tableName"
    class="manage-table-header"
  >
    {{ databaseConfig.tableName }}
  </div>
  <div class="container">
    <!-- 添加数据源 -->
    <div class="custom-tree-container" v-if="!databaseConfig">
      <div class="tree-header">
        入库表
        <i class="el-icon-plus" @click="addTree(node, data)"></i>
      </div>
      <el-tree
        :data="data"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span v-if="!data.isEdit" :title="node.label">{{
              node.label
            }}</span>
            <el-input
              v-else
              size="mini"
              style="width: 150px"
              @change="(value) => changeEditTree(value, data)"
              v-model="node.label"
            ></el-input>
            <i class="el-icon-edit" @click="editTree(node, data)"></i>
            <i class="el-icon-delete" @click="removeTree(node, data)"></i>
          </span>
        </template>
      </el-tree>
    </div>
    <div style="flex:1">
      <div class="database-dialog">
        <el-button type="primary" size="small" @click="addTableData">
          新建
        </el-button>
      </div>
      <gz-table :config="config">
        <template #handle="{ row: scope }">
          <el-button type="primary" size="small" @click="editTableList(scope)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="removeTableList(scope)">
            删除
          </el-button>
        </template>
      </gz-table>

      <!-- 新建列 弹框 -->
      <el-dialog :title="dialogTitle" v-model="dialogVisible" width="400px">
        <el-form
          :model="tableForm"
          :rules="rules"
          ref="tableFormRef"
          label-width="80px"
        >
          <el-form-item label="列名" prop="columnName">
            <el-input
              v-model="tableForm.columnName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="列类型" prop="columnType">
            <el-select
              v-model="tableForm.columnType"
              placeholder="请选择列类型"
              style="width:100%"
            >
              <el-option
                v-for="item in columnTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="最大长度">
            <el-input
              v-model="tableForm.charOctetLength"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否自增">
            <el-radio-group v-model="tableForm.autoincrement">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否主键">
            <el-radio-group v-model="tableForm.primaryKey">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="列说明">
            <el-input
              type="textarea"
              :autosize="{ minRows: 4 }"
              placeholder="请输入列说明"
              v-model="tableForm.remarks"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit"> 确 定 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
  <p>表备注：</p>
  <el-input
    type="textarea"
    :autosize="{ minRows: 4, maxRows: 6 }"
    placeholder="请输入表备注"
    v-model="tableRemarks"
  >
  </el-input>
</template>

<script>
import gzTable from "@/components/table/index.vue";

import { ref, reactive, toRefs, onMounted } from "vue";
var validateColumnName = (rule, value, callback) => {
  if (!isNaN(parseInt(value, 10))) {
    callback(new Error("表列名不能为数字！"));
  } else {
    callback();
  }
};
export default {
  components: { gzTable },
  props: {
    databaseConfig: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, ctx) {
    const dialogVisible = ref(false);
    const dialogTitle = ref("新建");
    const tableFormRef = ref(null);
    const state = reactive({
      rules: {
        columnName: [
          { required: true, validator: validateColumnName, trigger: "blur" }
        ],
        columnType: [
          { required: true, message: "请输入列类型", trigger: "change" }
        ]
      },
      tableRemarks: "", // 表备注
      columnTypeList: [
        {
          label: "INTEGER",
          value: "INTEGER"
        },
        {
          label: "BIGINT",
          value: "BIGINT"
        },
        {
          label: "FLOAT",
          value: "FLOAT"
        },
        {
          label: "DOUBLE",
          value: "DOUBLE"
        },
        {
          label: "DECIMAL",
          value: "DECIMAL"
        },
        {
          label: "DATE",
          value: "DATE"
        },
        {
          label: "TIME",
          value: "TIME"
        },
        {
          label: "YEAR",
          value: "YEAR"
        },
        {
          label: "DATETIME",
          value: "DATETIME"
        },
        {
          label: "TIMESTAMP",
          value: "TIMESTAMP"
        },
        {
          label: "VARCHAR",
          value: "VARCHAR"
        },
        {
          label: "MEDIUMTEXT",
          value: "MEDIUMTEXT"
        },
        {
          label: "LONGTEXT",
          value: "LONGTEXT"
        }
      ],
      tableForm: {
        columnName: "",
        columnType: "",
        primaryKey: false,
        charOctetLength: "",
        autoincrement: false,
        remarks: ""
      },
      data: [],
      count: 1,
      config: {
        // 表格样式
        style: {
          stripe: true,
          border: true,
          maxHeight: 360
        },
        loading: false,
        // 列
        column: [
          {
            prop: "columnName",
            label: "列名",
            width: 100,
            formatter(value) {
              return value.columnName || "-";
            }
          },
          {
            prop: "columnType",
            label: "列类型",
            width: 150,
            formatter(value) {
              return value.columnType || "-";
            }
          },
          {
            prop: "charOctetLength",
            label: "最大长度",
            width: 100,
            formatter(value) {
              return value.charOctetLength || "-";
            }
          },
          {
            prop: "autoincrement",
            label: "是否自增",
            width: 80,
            formatter(value) {
              return value.autoincrement === true ? "是" : "否";
            }
          },
          {
            prop: "remarks",
            label: "列说明",
            width: 150,
            formatter(value) {
              return value.remarks || "-";
            }
          },
          {
            prop: "primaryKey",
            label: "是否主键",
            width: 80,
            formatter(value) {
              return value.primaryKey === true ? "是" : "否";
            }
          },
          {
            type: "operate",
            label: "操作",
            width: 150,
            fixed: "right",
            slotName: "handle"
          }
        ],
        tableData: []
      }
    });
    onMounted(() => {
      if (props.databaseConfig) {
        state.config.tableData = props.databaseConfig.tableData;
        state.tableRemarks = props.databaseConfig.remarks;
      }
    });
    // 新建列结构 弹框
    const addTableData = () => {
      dialogVisible.value = true;
      vm.$nextTick(() => {
        tableFormRef.value.clearValidate();
      });
      dialogTitle.value = "新建";
      state.tableForm = {
        columnName: "",
        columnType: "",
        primaryKey: false,
        charOctetLength: "",
        autoincrement: false,
        remarks: ""
      };
    };
    // 编辑列 表结构
    const editTableList = (rowData) => {
      dialogVisible.value = true;
      dialogTitle.value = "编辑";
      state.tableForm = vm.$tool.deepClone(rowData);
    };
    // 删除列 表结构
    const removeTableList = (rowData) => {
      // 获取当前列索引
      let findIndex = state.config.tableData.findIndex(
        (tItem) => tItem.columnName == rowData.columnName
      );
      if (findIndex > -1) {
        state.config.tableData.splice(findIndex, 1);
      }
    };
    const addTree = () => {
      vm.$prompt("请输入表名称", "新建", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          if (!value) {
            vm.$message.warning("表名称不能为空！");
            return false;
          }
          state.data.push({
            id: state.count,
            label: value,
            isEdit: false,
            children: []
          });
          state.count++;
        })
        .catch(() => {});
    };
    const changeEditTree = (value, data) => {
      data.label = value;
      data.isEdit = false;
    };
    const editTree = (node, data) => {
      data.isEdit = !data.isEdit;
    };
    const removeTree = (node, data) => {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
      state.data = [...state.data];
    };
    const handleNodeClick = (data) => {};
    const submit = () => {
      tableFormRef.value.validate((valid) => {
        if (valid) {
          dialogVisible.value = false;
          // 新建/编辑
          if (dialogTitle.value == "新建") {
            state.config.tableData.push(state.tableForm);
          } else {
            let findIndex = state.config.tableData.findIndex(
              (t) => t.id == state.tableForm.id
            );
            if (findIndex > -1) {
              state.config.tableData[findIndex] = vm.$tool.deepClone(
                state.tableForm
              );
            }
          }
        } else {
          return false;
        }
      });
    };
    return {
      dialogTitle,
      dialogVisible,
      tableFormRef,
      ...toRefs(state),
      addTableData,
      editTableList,
      removeTableList,
      addTree,
      changeEditTree,
      editTree,
      removeTree,
      handleNodeClick,
      submit
    };
  }
};
</script>

<style scoped>
.manage-table-header {
  padding: 10px 0 10px 10px;
  background: #cccccc7a;
  margin-bottom: 15px;
}
.container {
  display: flex;
  justify-content: space-between;
}
.tree-header .el-icon-plus {
  margin-left: 20px;
  font-size: 16px;
  cursor: pointer;
}
.custom-tree-container >>> .el-tree-node__expand-icon.is-leaf {
  display: none;
}
.custom-tree-container {
  flex: 1;
  margin-right: 10px;
}
.custom-tree-container .el-icon-edit {
  margin-left: 5px;
}
.custom-tree-container .el-icon-delete {
  margin-left: 5px;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.custom-tree-node span {
  max-width: 150px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
/* 列区域 */
.database-dialog {
  margin-bottom: 15px;
}
</style>
